<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        class="cat_opt"
        title="警告:只允许编辑第三级"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedCateKeys"
            :options="catelist"
            :props="cateProps"
            @change="cateChanged"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDiabled"
            @click="addDialogVisible = true"
            >添加动态参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" stripe style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 增加标签 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  class="input-new-tag"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="分类参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  round
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑按钮</el-button
                >
                <el-button
                  type="danger"
                  round
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除按钮</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDiabled"
            @click="addDialogVisible = true"
            >添加静态属性</el-button
          >
          <!-- 静态属性面板表格 -->
          <el-table :data="onlyTableData" stripe style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签渲染 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 增加标签 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  class="input-new-tag"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="分类属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  round
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑按钮</el-button
                >
                <el-button
                  type="danger"
                  round
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除按钮</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      // 商品分类所在数组
      catelist: [],
      //级联选择框配置属性
      cateProps: {
        //选中的值
        value: 'cat_id',
        //看到的值
        label: 'cat_name',
        //父子嵌套
        children: 'children',
      },
      //级联选择框选中的id
      selectedCateKeys: [],
      //默认激活的页签页
      activeName: 'many',
      //动态参数的数据
      manyTableData: [],
      //静态属性的数据
      onlyTableData: [],
      //添加对话框
      addDialogVisible: false,
      //添加数据的表单
      addForm: {},
      //表单的校验
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
        ],
      },
      //修改属性的表单
      editForm: {},
      //表单的校验
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
        ],
      },
      //修改对话框
      editDialogVisible: false,
    }
  },

  methods: {
    //   获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类失败!!!!!')
      this.catelist = res.data
      console.log(this.catelist)
    },
    cateChanged() {
      this.getParamter()
    },
    //页签切换
    handleTabClick() {
      this.getParamter()
      console.log(this.activeName)
    },
    //获取参数的
    async getParamter() {
      //证明选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //   console.log(this.selectedCateKeys)
      //根据所处的分类id ，以及激活的状态，发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      //每次经过一次for循环，就会拿到一个item，每次拿到一个item，就会将attr_vals用split进行分割
      //将原本的字符串，变成数组
      res.data.forEach((item) => {
        //这里先去判断是否为空，如果为空直接返回一个空数组，如果不进行判断则 空字符串会出现一个空白标签
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //控制文本框的显示与隐藏
        item.inputVisible = false
        //文本框中的值
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //监听 添加属性的对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //点击添加分类
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.getParamter()
        this.addDialogVisible = false
      })
    },
    //监听 添加属性的对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //点击 修改
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        console.log(this.editForm)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getParamter()
      })
    },
    //点击 打开修改对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/` + id,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error('获取属性失败')
      this.editForm = res.data
    },
    deleteParams(attr_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.getParamter()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //显示标签输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框获取焦点
      //$nextTick方法作用 只有当页面元素重新渲染之后，才会回调指定函数中的代码
      this.$nextTick(_ => {
        //因为input是一个组件，只有先将这个组件拿到，才能拿到原生dom
          this.$refs.saveTagInputRef.$refs.input.focus();
        });
    },
    //文本框失去焦点或者是按下enter都会触发
    async handleInputConfirm(row) {
      //trim去除字符串两端的空格
      if(row.inputValue.trim().length === 0){
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return，输入的正常需要做后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //发起请求，保存到数据库中
      this.saveArrVals(row)
      
      
    },
    //保存参数项的修改
    async saveArrVals(row){
      const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        //我们这里是数组，而数据库中是字符串，需要将其进行拼接
        attr_vals:row.attr_vals.join(',')
      })
      if(res.meta.status !== 200) return this.$message.error("修改参数项失败")
      this.$message.success("修改参数项成功")
    },
    //删除标签
    handleClose(i,row){
      //splice表示删除从i开始的多少个数组
      row.attr_vals.splice(i,1)
      this.saveArrVals(row)

    }
  },
  computed: {
    isBtnDiabled() {
      //根据级联选择器是否选择三级分类 禁用，如果需要禁用，则返回true，否则返回false
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    //所选分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    },
    //判断选中的对话框
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>